package com.weixin.mp.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.spec.AlgorithmParameterSpec;

/**
 * 微信小程序加解密工具类
 */
@Slf4j
public class WxCryptUtils {
    
    /**
     * 解密微信加密数据
     * @param sessionKey 会话密钥
     * @param encryptedData 加密数据
     * @param iv 加密算法的初始向量
     * @return 解密后的JSON字符串
     */
    public static String decrypt(String sessionKey, String encryptedData, String iv) {
        try {
            // 被加密的数据
            byte[] dataByte = Base64.decodeBase64(encryptedData);
            // 加密秘钥
            byte[] keyByte = Base64.decodeBase64(sessionKey);
            // 偏移量
            byte[] ivByte = Base64.decodeBase64(iv);
            
            // 如果密钥不足16位，就补足
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            
            // 初始化
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(ivByte);
            cipher.init(Cipher.DECRYPT_MODE, spec, paramSpec);
            
            // 执行解密
            byte[] resultByte = cipher.doFinal(dataByte);
            if (resultByte != null && resultByte.length > 0) {
                return new String(resultByte, StandardCharsets.UTF_8);
            }
            return null;
        } catch (Exception e) {
            log.error("微信数据解密异常", e);
            return null;
        }
    }
} 